import wtforms
from wtforms.validators import Email, Length, EqualTo, InputRequired

from exts import db
from models.user_model import UserModel
from models.email_captcha_model import EmailCaptchaModel

class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email("Invalid email")])
    captcha = wtforms.StringField(validators=[Length(min=4,max=4,message="Invalid captcha code")])
    username = wtforms.StringField(validators=[Length(min=3, max=20, message="Invalid username")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="Invalid password")])
    password_confirm = wtforms.StringField(validators=[EqualTo("password")])

    # 自定义验证:
    # 1 邮箱已经被注册
    def validate_email(self, field):
        email = field.data
        print(email)
        user = UserModel.query.filter_by(email=email).first()
        print(user)
        if user:
            raise wtforms.ValidationError(message="This email is already registered.")

    def validate_captcha(self, field):
        captcha = field.data
        email = self.email.data
        email_captcha = EmailCaptchaModel.query.filter_by(email=email,captcha=captcha).first()
        if not email_captcha:
            raise wtforms.ValidationError(message="Email or Captcha code is invalid.")
        # delete
        else:
            db.session.delete(email_captcha)
            db.session.commit()

class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email("Invalid email")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="Invalid password")])


class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[Length(min=3, max=100, message="Invalid title")])
    content = wtforms.StringField(validators=[Length(min=3,  message="Invalid content")])


class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=3, message="Invalid content")])
    question_id = wtforms.IntegerField(validators=[InputRequired(message="Required question id")])